package com.atguigu.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Flink02_Stream_WordCount_Bounded {
    public static void main(String[] args) throws Exception {
        //1.获取Flink 流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //将并行度设置为1
        env.setParallelism(1);

        //2.获取文件中的数据 有界数据
        DataStreamSource<String> wordDStream = env.readTextFile("input/word.txt");

        //3.将每一行数据按照空格切分，切出每一个单词，然后组成Tuple2元组返回
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordToOneDStream = wordDStream.flatMap(new MyFlatMap());

        //4.将相同单词的数据聚合到一起
//        KeyedStream<Tuple2<String, Integer>, Tuple> keyedStream = wordToOneDStream.keyBy(0);
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = wordToOneDStream.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            /**
             * 指定key
             * @param value 流中的数据
             * @return
             * @throws Exception
             */
            @Override
            public String getKey(Tuple2<String, Integer> value) throws Exception {
                return value.f0;
            }
        });

        //5.累加计算
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = keyedStream.sum("f1");

        //6.打印到控制台
        result.print();

        //7.执行 生成一个job
        env.execute();
    }

    public static class MyFlatMap implements FlatMapFunction<String, Tuple2<String,Integer>>{

        @Override
        public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
            //1.将数据按照空格切分
            String[] words = value.split(" ");
            //2.遍历得到每一个单词并转为Tuple2元组
            for (String word : words) {
                out.collect(Tuple2.of(word,1));
            }
        }
    }
}
